package com.woniuxy.common.utils;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

@Component
public class JWTUtils {
	private static final String SECRET = "ysh";
	private static final String ISSUSER = "yueshenghuo";
	//token过期时间
	private static final long EXPIRETIME = 24 * 60 * 60 * 1000;

	// 创建token
	public static String createToken(String userId) {
		Algorithm algorithm = Algorithm.HMAC256(SECRET);
		String jwt = JWT.create()
				.withIssuer(ISSUSER)
				.withIssuedAt(new Date())
				.withExpiresAt(new Date(new Date().getTime() + EXPIRETIME))
				.withClaim("userId", userId)
				.sign(algorithm);
		return jwt;
	}

	// 解密验证
	public static void verify(String token) throws Exception{
		Algorithm algorithm = Algorithm.HMAC256(SECRET);
		JWTVerifier verifier = JWT.require(algorithm)
				.withIssuer(ISSUSER)
				.build();
			verifier.verify(token);
			// 未抛异常，则验证成功
	}

	// 获取用户信息
	public static String getUserId(String token) {
		try {
			return JWT.decode(token).getClaim("userId").asString();
		} catch (JWTDecodeException e) {
			System.out.println("该用户不存在");
		}
		return "";
	}
	// 获取用户信息
	public static String getmyUserId(String token) {
		try {
			return JWT.decode(token).getClaim("userId").asString();
		} catch (JWTDecodeException e) {
			System.out.println("该用户不存在");
		}
		return "";
	}
	/*
	 * public static void main(String[] args) { String token = createToken("lisi");
	 * System.out.println(token); System.out.println(verify(token));
	 * System.out.println(getUname(token)); }
	 */
}
